/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vastcm.stuhealth.client;

import com.vastcm.stuhealth.client.entity.ServerSetting;
import com.vastcm.stuhealth.client.entity.service.IServerSettingService;
import com.vastcm.stuhealth.client.entity.service.core.ICoreService;
import com.vastcm.stuhealth.client.framework.ui.EditUI;
import com.vastcm.stuhealth.client.utils.ExceptionUtils;

import java.awt.Dimension;
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.List;

import javax.swing.JOptionPane;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author house
 */
public class ServerSettingPanel extends EditUI<ServerSetting> {
	
	private Logger logger = LoggerFactory.getLogger(ServerSettingPanel.class);

    /**
     * Creates new form ServerSettingPanel
     */
    public ServerSettingPanel() {
        initComponents();
    }
    
    @Override
    public void loadData() {
        List<ServerSetting> ls = getService().getAll();
        if(ls != null && !ls.isEmpty()) {
            data = ls.get(0);
            txtSrvIP.setText(data.getServerIp());
            txtPort.setText(data.getServerPort());
        }
    }

    @Override
    public void storeData() {
        String ip = txtSrvIP.getText();
        if(ip != null && !ip.isEmpty()) {
            ip = ip.trim();
        }
        data.setServerIp(ip);
        String port = txtPort.getText();
        if(port != null && !port.isEmpty()) {
            port = port.trim();
        }
        data.setServerPort(port);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtSrvIP = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtPort = new javax.swing.JTextField();
        jToolBar1 = new javax.swing.JToolBar();
        jToolBar1.setFloatable(false);
        btnSave = new javax.swing.JButton();
        btnTestConn = new javax.swing.JButton();

        setPreferredSize(new Dimension(280, 180));
        setLayout(new java.awt.BorderLayout());

        jPanel1.setLayout(null);

        jLabel1.setText("服务器IP地址");
        jPanel1.add(jLabel1);
        jLabel1.setBounds(20, 20, 80, 25);
        jPanel1.add(txtSrvIP);
        txtSrvIP.setBounds(110, 20, 160, 25);

        jLabel2.setText("端口号");
        jPanel1.add(jLabel2);
        jLabel2.setBounds(20, 60, 80, 25);
        jPanel1.add(txtPort);
        txtPort.setBounds(110, 60, 160, 25);

        add(jPanel1, java.awt.BorderLayout.CENTER);

        jToolBar1.setRollover(true);

        btnSave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/system_save.gif"))); // NOI18N
        btnSave.setText("保存");
        btnSave.setFocusable(false);
        btnSave.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnSave.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });
        jToolBar1.add(btnSave);

        btnTestConn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/computer_connect.png"))); // NOI18N
        btnTestConn.setText("测试连接");
        btnTestConn.setFocusable(false);
        btnTestConn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnTestConn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnTestConn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnTestConnActionPerformed(evt);
            }
        });
        jToolBar1.add(btnTestConn);

        add(jToolBar1, java.awt.BorderLayout.NORTH);
    }// </editor-fold>//GEN-END:initComponents

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        try {
            save();
        } 
        catch (Exception ex) {
            ExceptionUtils.writeExceptionLog(logger, ex);
            JOptionPane.showMessageDialog(this, "保存失败：" + ex.getMessage());
        }
    }//GEN-LAST:event_btnSaveActionPerformed

    private void btnTestConnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTestConnActionPerformed
    	try {
			InetAddress ad = InetAddress.getByName(txtSrvIP.getText());
			Socket s = new Socket();
			s.connect(new InetSocketAddress(ad, Integer.valueOf(txtPort.getText())), 3000);
			s.close();
			JOptionPane.showMessageDialog(this, "连接服务器 成功！");
		} 
    	catch (UnknownHostException e) {
			ExceptionUtils.writeExceptionLog(logger, e);
			JOptionPane.showMessageDialog(this, "连接服务器 失败！");
		} 
    	catch (NumberFormatException e) {
    		ExceptionUtils.writeExceptionLog(logger, e);
			JOptionPane.showMessageDialog(this, "端口号格式 有误！");
		} 
    	catch (IOException e) {
    		ExceptionUtils.writeExceptionLog(logger, e);
			JOptionPane.showMessageDialog(this, "连接服务器 失败！");
		}

    }//GEN-LAST:event_btnTestConnActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnSave;
    private javax.swing.JButton btnTestConn;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JTextField txtPort;
    private javax.swing.JTextField txtSrvIP;
    // End of variables declaration//GEN-END:variables

    @Override
    public ICoreService<ServerSetting> getService() {
        return AppContext.getBean("serverSettingService", IServerSettingService.class);
    }
}
